package gptliaotiantest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.TimeUnit;

public class ChatServer {

    private static final Logger logger = LoggerFactory.getLogger(ChatServer.class);

    public static void main(String[] args) {
        new ChatServer().startServer();
    }

    public void startServer() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LineBasedFrameDecoder(8)); // 使用换行符分隔消息
                            ch.pipeline().addLast(new StringDecoder()); // 将字节数据转换为字符串
                            ch.pipeline().addLast("encoder", new StringEncoder());
                            ch.pipeline().addLast(new IdleStateHandler(0, 0, 5)); // 5秒内没有读写操作触发ALL_IDLE事件
                            ch.pipeline().addLast(new ChatServerHandler()); // 自定义处理消息的处理器
                        }
                    });

            Channel serverChannel = bootstrap.bind(8080).sync().channel();
            serverChannel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    private static class ChatServerHandler extends SimpleChannelInboundHandler<String> {

        private static Map<String,UserInfo> userInfoMap = new HashMap();
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            // 收到客户端消息，广播给所有客户端
            UserInfo nowUserInfo = userInfoMap.get(ctx.channel().id().asLongText());
            if (nowUserInfo.name == null) {
                logger.info("客户端设置昵称name={}",msg);
                nowUserInfo.name=msg;
            } else {
                logger.info("客户端发来消息 msg={},昵称={}",msg,nowUserInfo.name);
                for (UserInfo userInfo : userInfoMap.values()) {
                    if (ctx.channel() != userInfo.channel) {
                        userInfo.channel.writeAndFlush(userInfo.name + ": " + msg + "\n");
                    }
                }
            }
        }

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            Channel incoming = ctx.channel();

            userInfoMap.put(incoming.id().asLongText(),new UserInfo(incoming));
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            Channel incoming = ctx.channel();

            userInfoMap.remove(incoming.id().asLongText());
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            Channel incoming = ctx.channel();
            logger.info("[SERVER] {} 在线",incoming.remoteAddress());
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            Channel incoming = ctx.channel();
            logger.info("[SERVER] {} 掉线",incoming.remoteAddress());
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                if (e.state() == IdleState.ALL_IDLE) {
                    // 处理空闲状态事件，例如发送心跳包或关闭连接
                    // 在这里可以执行适当的操作
                    ctx.writeAndFlush("evet\n");
                    logger.info("{} 触发空闲事件",ctx.channel().remoteAddress());
                }
            }
        }
    }
}
